package biz.almas.uycnr.crawler.dao;

import java.util.List;

import org.apache.log4j.Logger;

import cn.ffcs.memory.ColumnHandler;
import cn.ffcs.memory.Memory;

import biz.almas.uycnr.crawler.dao.factory.MemoryFactory;
import biz.almas.uycnr.crawler.entity.Appendix;

/**
 * @Description: 附件
 * @Copyright: Copyright (c) 2015 XinJiang Almas Software All Rights Reserved
 * @Company: XinJiang Almas Software
 * @author Ansar786 Nov 19, 2015
 * @version V1.0
 * @history:
 * 
 */
public class AppendixDao {
	// 定义日志输出对象
	private static Logger logger = Logger.getLogger(AppendixDao.class);
	// 获取Memory对象
	private Memory memory = MemoryFactory.getInstance();

	public void storeAppendixs(List<Appendix> appendixs) {
		if (appendixs != null && appendixs.size() > 0) {
			for (Appendix appendix : appendixs) {
				int id = getIdByAppendixId(appendix.getAppendixId());
				if (id > 0) {
					appendix.setId(id);
					updateAppendix(appendix);
				} else {
					saveAppendix(appendix);
				}
			}
		}
	}

	/**
	 * Ansar786 Nov 24, 2015
	 * 
	 * @param appendix
	 */
	public void saveAppendix(Appendix appendix) {
		try {
			memory.create(Appendix.class, appendix);
		} catch (Exception e) {
			logger.error("添加文档附件时出错：" + e.toString() + "\n==================");
		}
	}

	/**
	 * Ansar786 Nov 24, 2015
	 * 
	 * @param appendix
	 */
	public void updateAppendix(Appendix appendix) {
		try {
			memory.update(Appendix.class, appendix);
		} catch (Exception e) {
			logger.error("修改文档附件时出错：" + e.toString() + "\n=================");
		}
	}

	/**
	 * Ansar786 Nov 24, 2015
	 * 
	 * @param appendix
	 * @return
	 */
	public int getIdByAppendixId(int appendixId) {
		try {
			Integer id = memory.query(
					"select id from appendix where appendix_id = ?",
					new ColumnHandler<Integer>(Integer.class), appendixId);
			if (id == null) {
				return 0;
			}

			return id;
		} catch (Exception e) {
			logger.error("获取附件时出错：" + e.toString());
			return 0;
		}
	}
}
